package com.caishi.lkx.gateway;


import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import com.zzw.common.Result;
import com.zzw.common.handler.ServletInvocableHandlerMethodCallback;
import com.zzw.common.handler.ServletInvocableHandlerPipeline;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.HandlerMethod;


import java.security.*;
import java.util.Map;


@Configuration
@Slf4j
public class ResultServletInvocableHandlerMethodHandler implements ServletInvocableHandlerPipeline {
    private final String pubkey = "MIIBCgKCAQEAuTOH+2+MMSw/f85ngIOcewzrHno++0sb+E3y8LAtY1htgaz9uiYz" +
            "51yGj/XHnUSkvaSzyS6pVeeXQjdEn8Ual4Tty4bYFGi6z24vV6e8BlPDBGQSAuM7" +
            "KRQhFyeSSvVkRrdPZ0IckSLWusjCEt7B280xx3xB6bNFXbFuGdpIPIfmR/vT02QD" +
            "k4PFoet6r2h3Znqh2+8/mQ6TIJCGS7vwTzHwH0hJaSJMk+VPfvmIX1xwDkNKxOOV" +
            "lMeXGULNj8n4uBMat0wNB4G+nhxgO5MNBn/WpJnmGJkjjo18INenjV9867qkgLUp" +
            "jlFT0iSXvHiFPPeChh6kwV6gCK7zkfRfaQIDAQAB";

    @Override
    public int getOrder() {
        return 20;
    }

    static {
        try {
            Signature sha256withRSA = Signature.getInstance("SHA256withRSA");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Object work(HandlerMethod handlerMethod,
                       Object[] args,
                       NativeWebRequest request,
                       Map<Object, Object> workContext,
                       ServletInvocableHandlerMethodCallback callback) throws Exception {
        Object result = callback.get();
        String jwt = request.getHeader("Authorization");
        if (StrUtil.isBlank(jwt)) {
            return result;
        }
        jwt = jwt.substring(6).trim();
        JWT jwt1 = JWT.of(jwt);
        JWTPayload payload1 = jwt1.getPayload();
        String orgCode = (String) payload1.getClaim("OrgCode");
        if (null != orgCode) {
            ZhituResult instance = ZhituResult.getInstance();
            if (result instanceof Result r) {
                instance.setData(r.getData());
                instance.setStatusCode(r.getCode() == 1 ? 200 : r.getCode());
                instance.setSucceeded(r.getSuccess());
                instance.setExtras(r.getMessage());
                instance.setTimestamp(System.currentTimeMillis());
            }
            return instance;
        } else {
            return result;
        }
    }
}
